package com.meixiang.fragment.collect;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;

import com.google.gson.Gson;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.CollectActivity;
import com.meixiang.activity.homes.service.ReservationActivity;
import com.meixiang.activity.homes.service.ServiceDetailActivity;
import com.meixiang.activity.homes.shopping.GoodsDetailActivity;
import com.meixiang.adapter.collect.SwipeAdapter;
import com.meixiang.adapter.collect.SwipeListView;
import com.meixiang.dialog.BuyGoodsDialogFragment;
import com.meixiang.entity.collect.CollectDateEntity;
import com.meixiang.entity.collect.CollectEntity;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 全部
 */
public class AllCollectFragment extends BaseFragment implements OnRefreshListener,OnLoadMoreListener{
    private CollectActivity mActivity;

    @Bind(R.id.swipe_target)
    SwipeListView mSwipeTarget;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    SwipeAdapter mAdapter;
    private String favType = "0" ;
    private CollectEntity mCollectEntity ;
    private List<CollectDateEntity> mCollectList ;
    public AllCollectFragment() {

    }
    public static AllCollectFragment getInstance(String favType){
        AllCollectFragment fragment=new AllCollectFragment();
        Bundle bundle=new Bundle();
        bundle.putString("favType", favType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity= (CollectActivity) getActivity();
        Bundle bundle=getArguments();
        favType=bundle.getString("favType");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_all_collect, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initTitle() {

    }
    @Override
    protected void initView() {
        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);
    }

    @Override
    protected void setData() {
        mAdapter = new SwipeAdapter(activity);
        mAdapter.setOnRightItemClickListener(new SwipeAdapter.onRightItemClickListener() {

            @Override
            public void onRightItemClick(View v, int position) {
                cancelMatch(position);
            }

            @Override
            public void onBtnItemClick(View v, int position) {
                if ("2".equals(mAdapter.getData().get(position).getFavType())) { //商品收藏
                    Bundle bundle = new Bundle();
                    bundle.putString("goodsId", mCollectList.get(position).getFavId());
                    bundle.putString("price", mCollectList.get(position).getFavStorePrice());
                    bundle.putString("type", GlobalType.ADD_RESERVATION);

                    //bundle.putString("isMainStore", mCollectList.get(position).getIsMainStore());
                    bundle.putString("goodsBody", mCollectList.get(position).getFavName());
                    bundle.putString("goodsImage",  mCollectList.get(position).getFavImage());
                    startActivity(bundle,ReservationActivity.class);
                } else if ("1".equals(mAdapter.getData().get(position).getFavType())) {
                    BuyGoodsDialogFragment
                            .newInStance(true, mCollectList.get(position).getFavId() + "", null, 1)
                            .show(activity.getSupportFragmentManager(), "Collect");
                }
            }
        });
        showLoading();
        mSwipeTarget.setAdapter(mAdapter);
        mSwipeTarget.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent();
                if (mAdapter.getData().get(position).getFavType().equals("1")){
                    intent.putExtra("goods_id",mAdapter.getData().get(position).getFavId()+"");
                    intent.setClass(activity, GoodsDetailActivity.class);
                }else{
                    intent.putExtra("goodsId",mAdapter.getData().get(position).getFavId()+"");
                    intent.setClass(activity, ServiceDetailActivity.class);
                }
                startActivity(intent);
            }
        });
        mSwipeTarget.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (view.getLastVisiblePosition() == view.getCount() - 1 && !ViewCompat.canScrollVertically(view, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
         getData(1, true);
    }

    private void getData(int pageNo, final boolean isDownPull){
        HttpParams params = new HttpParams();
        params.put("favType",favType);
        params.put("pageSize", "10");
        params.put("pageNo", pageNo+"");
        HttpUtils.post(Config.COLLECT_LIST, params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (isDownPull) {
                    mAdapter.clearData();
                }
                mCollectEntity = new Gson().fromJson(result.toString(), CollectEntity.class);
                mCollectList = mCollectEntity.getmCollectDateList();
                if (mCollectList == null || mCollectList.size() == 0) {
                    showNoData("暂无收藏");
                } else {
                    removeStatus();
                    if (favType.equals("1")) {
                        for (int i = mCollectList.size() - 1; i >= 0; i--) {
                            if (!mCollectList.get(i).getFavType().equals("1")) {
                                mCollectList.remove(i);
                            }
                        }
                    } else if (favType.equals("2")) {
                        for (int i = mCollectList.size() - 1; i >= 0; i--) {
                            if (!mCollectList.get(i).getFavType().equals("2")) {
                                mCollectList.remove(i);
                            }
                        }
                    }
                    mAdapter.addData(mCollectList);
                }
            }

            @Override
            public void onError(String code, String message) {

                AbToastUtil.showToast(activity, message);

                showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getData(1, true);
                    }
                });
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onComplete(mRefresh);
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            if (mRefresh!=null){
                mRefresh.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mRefresh!=null){
                            mRefresh.setRefreshing(true);
                        }
                    }
                });
            }
        }
    }

    /**
     * 取消收藏
     */
    private void cancelMatch(final int position){
        HttpParams params = new HttpParams();
        params.put("favType",mCollectList.get(position).getFavType());
        params.put("favId",mCollectList.get(position).getFavId()+"");
        HttpUtils.post(Config.COLLECT_CANCEL, params, new HttpCallBack(activity,"正在取消收藏...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, "取消收藏成功");
                mAdapter.removeData(position);
                mActivity.getData();
                mSwipeTarget.hiddenRight(mSwipeTarget.getChildAt(position));
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity,message);
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLoadMore() {
        if (mCollectEntity.getPageNo()<mCollectEntity.getTotalPage()){
            getData(mCollectEntity.getPageNo()+1,false);
        }else{
            AbToastUtil.showToast(activity,"已无更多收藏");
            onComplete(mRefresh);
        }
    }

    @Override
    public void onRefresh() {
        getData(1,true);
    }
}
